package org.example.cloud.controller;

import org.example.cloud.bean.User;
import org.example.cloud.mapper.UserMapper;
import org.example.cloud.result.Result;
import org.example.cloud.service.implementation.FileFolderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ResistController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FileFolderService fileFolderService;
    @PostMapping("/api/register")
    @CrossOrigin(origins = "http://localhost:8080")
    public Result regist(@RequestBody User user) {

        // 1. 校验用户名是否为空
        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            return Result.error(400, "用户名不能为空");
        }

        // 2. 先查询用户名是否已存在
        User existingUser = userMapper.findByUsername(user.getUsername());
        if (existingUser != null) {
            // 用户名已存在，返回明确提示
            return Result.error(400, "用户名已存在，请更换");
        }

        // 3. 用户名不存在，执行插入
        try {
            userMapper.insertUser(user);
            fileFolderService.initFolder(user.getUsername());
            return Result.error(200, "注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            // 其他异常（如数据库连接问题）返回通用错误
            return Result.error(500, "注册失败：" + e.getMessage());
        }
    }
}